n = int(input())
a = []
visited = [False] * n
adj = [[] for i in range(n)]
for i in range(n):
x, y = map(int, input().split())
a.append([x, y])
for i in range(n):
for j in range(i + 1, n):
if a[i][0] == a[j][0] or a[i][1] == a[j][1]:
adj[i].append(j)
adj[j].append(i)
def dfs(v):
visited[v] = True
for u in adj[v]:
if not visited[u]:
dfs(u)
ans = 0
for i in range(n):
if not visited[i]:
ans += 1
dfs(i)
print(ans - 1)
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef pair<ll, ll> pi;
#define lll __int128_t
#define mp make_pair
#define pb push_back
#define F first
#define S second
#define SetBit(x, k) (x |= (1LL << k))
#define ClearBit(x, k) (x &= ~(1LL << k))
#define CheckBit(x, k) (x & (1LL << k))
#define debug(x) { cerr << #x << " = " << x << endl; }
const ll inf = 1LL<<60; //1.15e18
const ll md = 1000000007;
ll dx[]={0,1,0,-1};
ll dy[]={1,0,-1,0};
ll dxx[]={0,1,0,-1,1,1,-1,-1};
ll dyy[]={1,0,-1,0,1,-1,1,-1};
ll vis[1005];
void dfs(ll i, vector<vector<ll>>&g)
{
vis[i]=1;
for(auto x: g[i])
{
if(!vis[x])dfs(x,g);
}
}
void solve()
{
ll n; cin >> n;
vector<ll>x[1005],y[1005];
vector<vector<ll>>g(n+1);
for(ll i=1;i<=n;i++)
{
ll a, b; cin >> a >> b;
x[a].push_back(i);
y[b].push_back(i);
}
for(ll i=1;i<=1000;i++){
for(auto j: x[i])
{
for(auto k: x[i])
{
if(k==j)continue;
g[j].push_back(k);
g[k].push_back(j);
}
}
}
for(ll i=1;i<=1000;i++){
for(auto j: y[i])
{
for(auto k: y[i])
{
if(k==j)continue;
g[j].push_back(k);
g[k].push_back(j);
}
}
}
ll ans=-1;
for(ll i=1;i<=n;i++)
{
if(!vis[i])
{
ans++;
dfs(i,g);
}
}
cout<<ans;
}
int main()
{
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
ios_base::sync_with_stdio(false);
cin.tie(NULL);cout.tie(NULL);
ll T; T=1;
//cin >> T;
while(T--)
{
solve();
}
}
1660A - Vasya and Coins | 1660E - Matrix and Shifts |
1293B - JOE is on TV | 1584A - Mathematical Addition |
1660B - Vlad and Candies | 1472C - Long Jumps |
1293D - Aroma's Search | 918A - Eleven |
1237A - Balanced Rating Changes | 1616A - Integer Diversity |
1627B - Not Sitting | 1663C - Pōja Verdon |
1497A - Meximization | 1633B - Minority |
688B - Lovely Palindromes | 66B - Petya and Countryside |
1557B - Moamen and k-subarrays | 540A - Combination Lock |
1553C - Penalty | 1474E - What Is It |
1335B - Construct the String | 1004B - Sonya and Exhibition |
1397A - Juggling Letters | 985C - Liebig's Barrels |
115A - Party | 746B - Decoding |
1424G - Years | 1663A - Who Tested |
1073B - Vasya and Books | 195B - After Training |